package logic

import (
	"context"
	"errors"
	"fmt"
	"order_srv/model/mysql"
	"order_srv/pkg"
	"strconv"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddOrderLogic {
	return &AddOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddOrderLogic) AddOrder(in *order.AddOrderRequest) (*order.AddOrderResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{}
	err := user.FindInIdByUser(int(in.UserId))
	if err != nil {
		logx.Error("用户不存在")
		return nil, errors.New("请重新登录")
	}
	if user.UserStatus != 1 {
		logx.Error("账号已被冻结")
		return nil, errors.New("该账号已被冻结")
	}
	goods := mysql.Goods{}

	err = goods.FindInIdByGoods(in.GoodsId)
	if err != nil {
		logx.Error("商品Id不存在")
		return nil, errors.New("商品不存在")
	}
	sum := goods.GoodsPrice * int(in.Num)
	fmt.Println("价格" + strconv.Itoa(sum))

	number := pkg.NewNumber()
	pay, err := pkg.AliPay(goods.GoodsTitle, number, strconv.Itoa(goods.GoodsPrice))
	if err != nil {
		logx.Error("支付功能失败")
		return nil, errors.New("支付失败")
	}
	m := mysql.Order{
		UserId:      int(in.UserId),
		GoodsId:     int(goods.ID),
		GoodsNumber: number,
		GoodsTitle:  goods.GoodsTitle,
		GoodsPrice:  sum,
		GoodsStatus: goods.GoodsStatus,
		GoodsCover:  goods.GoodsCover,
		GoodsTypes:  goods.GoodsTypes,
	}
	err = m.AddOrder()
	if err != nil {
		logx.Error("订单入库失败")
		return nil, errors.New("生成订单失败")
	}

	return &order.AddOrderResponse{Url: pay}, nil
}
